package com.project.user.controller.controller;

import com.project.user.entity.LoginTokenExample;
import com.project.user.entity.entitly.LoginToken;
import com.project.user.entity.entitly.UserInfo;
import com.project.user.mapper.LoginTokenMapper;
import com.untils.MybatisClass;
import org.apache.ibatis.session.SqlSession;

import java.util.Date;

public class UserTokenController implements com.project.user.controller.UserTokenController {
    @Override
    public int CreateLoginToken(UserInfo userInfo, String loginIpv4, String loginIpaddress, String loginSuccessfully,String loginSessionId) throws Exception {
        int successfully = -1;
        if (userInfo != null) {
            SqlSession sqlSession = MybatisClass.getSqlSession();
            LoginTokenMapper userInfoMapper = sqlSession.getMapper(LoginTokenMapper.class);
            try {
                successfully = userInfoMapper.insert(new LoginToken(userInfo.getUserPhonenumber(), loginIpv4, loginIpaddress, loginSuccessfully,loginSessionId));
            } finally {
                sqlSession.close();
            }
        }
        return successfully;
    }

    @Override
    public LoginToken CheckLoginToken(UserInfo userInfo, String loginSuccessfully, String userSession) throws Exception {
        LoginToken CheckLoginToken = new LoginToken();
        SqlSession sqlSession = MybatisClass.getSqlSession();
        LoginTokenMapper userInfoMapper = sqlSession.getMapper(LoginTokenMapper.class);
        LoginTokenExample loginTokenExample = new LoginTokenExample();
        Date now = new Date(System.currentTimeMillis());

        if (userInfo.getUserId().length()>0 && userInfo.getUserId()!=null) {
            loginTokenExample.createCriteria().andIdIsNotNull().andLoginUseridEqualTo(userInfo.getUserId()).andLoginEffectivetimeGreaterThanOrEqualTo(now);
        } else if (loginSuccessfully != null) {
            loginTokenExample.createCriteria().andIdIsNotNull().andLoginIssuccessfullyEqualTo(loginSuccessfully).andLoginEffectivetimeGreaterThanOrEqualTo(now);
        } else if (userSession != null) {
            loginTokenExample.createCriteria().andIdIsNotNull().andLoginSessionIdEqualTo(userSession).andLoginEffectivetimeGreaterThanOrEqualTo(now);
        }
        // another type

        try {
            CheckLoginToken = userInfoMapper.selectByExample(loginTokenExample).get(0);
        } finally {
            sqlSession.commit();
            sqlSession.close();
        }
        return CheckLoginToken;
    }

    @Override
    public int updateLoginToken(LoginToken userToken) throws Exception {
        SqlSession sqlSession = MybatisClass.getSqlSession();
        int successfully = -1;
        LoginTokenMapper userInfoMapper = sqlSession.getMapper(LoginTokenMapper.class);
        try {
            successfully = userInfoMapper.updateByPrimaryKey(userToken);
        } finally {
            sqlSession.close();
        }
        return successfully;
    }
}
